package com.it2.pdfdemo.util;


import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * 文件下载
 */
public class FileDownload {

    /**
     * 文件下载到指定路径
     *
     * @param urlStr   链接
     * @param savePath 保存路径
     * @param filename 文件名
     * @throws Exception
     */
    public static void download(String urlStr, String savePath, String filename) throws IOException {
        //构造URL
        URL url = new URL(urlStr);
        URLConnection con = url.openConnection();
        con.setConnectTimeout(20 * 1000);
        //文件路径不存在 则创建
        File folder = new File(savePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //jdk 7 流自动关闭
        try (InputStream in = con.getInputStream();
             OutputStream out = new FileOutputStream(folder.getPath() + "\\" + filename)) {
            //创建缓冲区
            byte[] buff = new byte[1024];
            int n;
            // 开始读取
            while ((n = in.read(buff)) >= 0) {
                out.write(buff, 0, n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static void main(String[] args) throws Exception {
        download("https://www.baidu.com/img/flexible/logo/pc/peak-result.png", "d:\\test2\\", "baidu.png");
    }
}